package cn.hzh.forward.init;

import cn.hzh.forward.config.properties.FeishuConfigProperties;
import cn.hzh.forward.service.FeishuMsgService;
import com.github.jaemon.dinger.DingerSender;
import com.github.jaemon.dinger.core.entity.DingerRequest;
import com.github.jaemon.dinger.core.entity.enums.MessageSubType;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.EventMessage;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
@AllArgsConstructor
public class FeishuInit {
    private final DingerSender dingerSender;
    private final FeishuMsgService feishuMsgService;
    private final FeishuConfigProperties config;

    /**
     * 启动长连接，并注册事件处理器。
     */
    @PostConstruct
    public void feishuInit() {
        EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("", "")
                .onP2MessageReceiveV1(new ImService.P2MessageReceiveV1Handler() {
                    @Override
                    public void handle(P2MessageReceiveV1 event) {
                        System.out.printf("[ onP2MessageReceiveV1 access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                        String handleMessage = feishuMsgService.handleMessage(event);
                        if (handleMessage != null) {
                            sendDingMessage(handleMessage, event.getEvent().getMessage());
                        }
                    }
                })
                .build();
        com.lark.oapi.ws.Client wsClient = new com.lark.oapi.ws.Client.Builder(config.getAppId(), config.getAppSecret())
                .eventHandler(EVENT_HANDLER)
                .build();
        log.info("feishu wsClient init...");
        wsClient.start();

    }

    // 发送钉钉消息
    public void sendDingMessage(String content, EventMessage feishuMessage) {
        String messageId = feishuMessage.getMessageId();
        log.info("send ding message start, messageId: {}", messageId);
        sendDingMarkdownMessage(content);
        log.info("send ding message end, messageId: {}", messageId);
        // todo 发送成功后，需要更新数据库
    }

    // 发送钉钉Markdown消息
    private void sendDingMarkdownMessage(String content) {
        dingerSender.send(
                MessageSubType.MARKDOWN,
                DingerRequest.request(content, "财运享通")
        );
    }

    // 发送钉钉文本消息
    private void sendDingTextMessage(String content) {
        dingerSender.send(
                MessageSubType.TEXT,
                DingerRequest.request(content)
        );
    }

    // 发送钉钉图片消息
    private void sendDingImageMessage(String content) {
        dingerSender.send(
                MessageSubType.IMAGETEXT,
                DingerRequest.request(content)
        );
    }

}